package xin.qixia.robot.core;

import xin.qixia.robot.core.convert.MessageConverter;
import xin.qixia.robot.core.domain.RobotMessage;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 消息分发
 *
 * @author wangkaixin
 * @date 2025/5/23 14:41
 */
public class RobotMessageDispatcher {
    private final Map<String, List<RobotMessageHandler>> listeners = new ConcurrentHashMap<>();

    /**
     * 注册监听器
     */
    public void registerListener(String topic, RobotMessageHandler listener) {
        listeners.computeIfAbsent(topic, k -> new CopyOnWriteArrayList<>()).add(listener);
    }

    /**
     * 分发消息
     */
    public void dispatch(String topic, RobotMessage message) {
        listeners.getOrDefault(topic, Collections.emptyList())
                .forEach(handler -> handler.handle(message));
    }

    /**
     * 分发消息
     */
    public <T> void dispatch(T message, MessageConverter<T> converter) {
        listeners.getOrDefault("default", Collections.emptyList())
                .forEach(handler -> handler.handle(converter.convert(message)));
    }
}